package com.example.as_sum.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.example.as_sum.R;
import com.example.as_sum.application.AppApplication;
import com.example.as_sum.view.CustomProgressDialog;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


//这里是继承FragmentActivity，而默认的Activity是继承AppCompatActivity
//AppCompatActivity也是集成FragmentActivity的

//AppCompatActivity默认是有一个方法来实现取消标题的
//supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
//FragmentActivity可以直接调用requestWindowFeature(Window.FEATURE_NO_TITLE);

//抽象类不用非要集成
public abstract class RootActivity extends FragmentActivity {
    private final int REQUEST_CODE=1000;
    private final String Tga = RootActivity.this.getClass().getSimpleName();
    private boolean isForeGround;//判断是不是正在运行
    private InputMethodManager mInputMethodManager;
    private boolean isShowMsg = true;
    private CustomProgressDialog dialog;

     public final int READ_EXTERNAL_PERMISSIONS = 120;
     public final int WRITE_EXTERNAL_PERMISSIONS = 121;
     public final int PHONE_PERMISSIONS = 122;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(this instanceof MainActivity){

        }else{
            AppApplication.aContext.addActivity(this);
        }

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        //当该window在进行显示的时候，不允许截屏
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        //取消输入密码回显功能(需要权限WRITE_SETTINGS）
        //Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD, 0);
       //StatusBarCompat.compat(this,getResources().getColor(R.color.colorPrimary));
        checkPermission();
    }
    private void checkPermission(){
        //申请WRITE_SETTINGS权限
        if(Build.VERSION.SDK_INT >= 23) {
            if (Settings.System.canWrite(this)) {
                Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD, 0);
            } else {
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, REQUEST_CODE);
            }
        }else{
            Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD, 0);
        }
    }
    public void showLongMsg(String text) {
        if (isShowMsg) {
            Toast.makeText(getApplication(), text, Toast.LENGTH_LONG).show();
        }
    }

    public void showShortMsg(String text) {
        if (isShowMsg) {
            Toast.makeText(getApplication(), text, Toast.LENGTH_SHORT).show();
        }
    }
    public void showDialog(String text, boolean b) {

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new CustomProgressDialog(this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(b);

        if (!dialog.isShowing()) {
            dialog.show();
        }

        dialog.setText(text);

    }
    public void closeDialog() {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }

    }
    //隐藏系统键盘
    public void hintKb() {

        if (mInputMethodManager.isActive()) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
                                    .getWindowToken(),
                            0);
                }
            }

        }
    }
    public void initTitle(String text){
        initTitle(text,true);
    }
    public void initTitle(String text,boolean isShow){
        TextView tv=(TextView) this.findViewById(R.id.base_title);
        tv.setText(text);
        ImageView img=(ImageView)this.findViewById(R.id.base_back_img);
        if(isShow){
            img.setVisibility(View.VISIBLE);
        }else{
            img.setVisibility(View.INVISIBLE);
        }
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    //单击，隐藏系统键盘
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
                                    .getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case READ_EXTERNAL_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted 被允许
                    Toast.makeText(this, "READ_EXTERNAL允许", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // Permission Denied 被拒绝
                    Toast.makeText(this, "READ_EXTERNAL被拒绝1122", Toast.LENGTH_SHORT)
                            .show();
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }
                break;
            case WRITE_EXTERNAL_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted 被允许
                    Toast.makeText(this, "WRITE_EXTERNAL允许", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // Permission Denied 被拒绝
                    Toast.makeText(this, "WRITE_EXTERNAL被拒绝1122", Toast.LENGTH_SHORT)
                            .show();
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }
                break;
            case PHONE_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted 被允许
                    Toast.makeText(this, "PHONE权限允许", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // Permission Denied 被拒绝
                    Toast.makeText(this, "PHONE权限被拒绝2233", Toast.LENGTH_SHORT)
                            .show();
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==REQUEST_CODE){
            if (Build.VERSION.SDK_INT >= 23) {
                if (Settings.System.canWrite(this)) {
                    //检查返回结果
                    Toast.makeText(this ,"WRITE_SETTINGS succee", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "WRITE_SETTINGS failure", Toast.LENGTH_SHORT).show();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onStop() {
        isForeGround = AppApplication.aContext.isRunningForeground(this);
        if(!isForeGround)
        {
            Toast.makeText(RootActivity.this,"牛牛正在后台运行",Toast.LENGTH_LONG).show();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        AppApplication.aContext.removeActivity(this);
        super.onDestroy();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
//        if(hasFocus){
//            //有焦点
////            Patterns.PHONE;
////            Patterns.EMAIL_ADDRESS;
//        }else{
//            //无焦点
//            mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
//                            .getWindowToken(),
//                    InputMethodManager.HIDE_NOT_ALWAYS);
//        }
    }
}
